package com.kehutong.department.service;

import com.kehutong.common.DoveClient;
import com.kehutong.common.entity.Root;
import com.kehutong.common.errcode.Result;
import com.kehutong.common.util.Token;
import com.kehutong.department.entity.ThirdDepartment;
import com.kehutong.department.entity.ThirdEmployee;
import com.kehutong.department.entity.ThirdEnterpriseConfig;
import com.kehutong.department.util.DateUtils;
import com.kehutong.department.util.HttpUtils;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.util.IDGenerate;
import org.coraframework.util.UUIDGenerator;
import org.coraframework.util.secret.MD5;
import org.coraframework.util.time.TimeUtil;

import java.sql.Timestamp;
import java.util.*;

@WebService("/basic/Thirddepartment/service")
public class ThirdDepartmentService {
    private static final Logger logger = LoggerFactory.getLogger(ThirdDepartmentService.class);
    @Inject
    private JdbcSession jdbcSession;

    @Inject
    private DoveClient doveClient;

    /**
     * 同步部门数据
     * @return 同步结果
     */
   @ReqMapping("/Thirddepartment")
    public void Thirddepartment(Token token, JSONObject jsonObject) throws Exception {
        ThirdEnterpriseConfig thirdEnterpriseConfig = jdbcSession.findOne(ThirdEnterpriseConfig.class).eq("companyNo",token.getCompanyNo()).exe();
        Map<String, String>thirdDepartmentMap = getThirdDepartmentMap(token.getCompanyNo());  //企业关系map
        thirdEnterpriseConfig.setLepartmentLastTime(null);
        List<JSONObject> datas = new ArrayList<>();
        //多次请求中海中台，拉取所有数据
        for(int i=1;;i++){
            JSONObject result = analysisDepartmentData(i,thirdEnterpriseConfig,thirdDepartmentMap); //解析接口返回、数据入库、同步企微
            List<JSONObject> list = JSONObject.parseArray(result.getJSONArray("list").toJSONString(), JSONObject.class);
            datas.addAll(list);
            if(i >= result.getIntValue("pages")){
                break;
            }
        }
       System.out.println("-------------------------------------------部门数：" + datas.size());
        //删除原有关系数据
       List<ThirdDepartment> ThirdDepartmentList=jdbcSession.findArray(ThirdDepartment.class).exe();
           for(ThirdDepartment thirdDepartment:ThirdDepartmentList){
               jdbcSession.deleteById(thirdDepartment);
           }

       //删除原有部门数据
       JSONObject result = doveClient.post("/basic/department/service/ThriddeleteAll", (http) -> {
           http.setBody(null); });

       // 将获取到的数据进行分组处理
       Map<String, JSONObject> kht_zh_map = new HashMap<>(datas.size());
       datas.forEach(json->{
           String guid = json.getString("guid");
           if (!kht_zh_map.containsKey(guid)) {
               kht_zh_map.put(guid, json);
               String khtid= "0".equals(json.getString("parentCode")) ? "1" : IDGenerate.nextId();
               json.put("khtId", khtid);
               json.put("id", khtid);
           }
       });
       for (JSONObject json : datas) {
           List<String> parantIds = getparentIds(json, kht_zh_map);
           json.put("parent_ids", parantIds);
           JSONObject parent = kht_zh_map.get(json.getString("parentCode"));
           String parentCode = json.getString("parentCode");
           if (!"0".equals(parentCode)) {
               json.put("parent_id", parent.getString("khtId"));
           }
           JSONObject saveResult = doveClient.post("/basic/department/service/ThridSave", (http) -> {
               http.setBody(json.toJSONString()); });
           // 新增 ThirdDepartment 关系数据
           ThirdDepartment department = Pool.newInstance(ThirdDepartment.class);
           department.setThirdId(json.getString("guid"));
           department.setKhtId(json.getString("khtId"));
           jdbcSession.insert(department);
       }
       //批量把部门同步到企业微信

    }

    private List<String> getparentIds(JSONObject jsonObject, Map<String, JSONObject> allMap) {
        List<String> parentIds = new ArrayList<>(8);
        String parentCode = jsonObject.getString("parentCode");
        parentIds.add(jsonObject.getString("khtId"));
        while (!"0".equals(parentCode)) {
            jsonObject = allMap.get(parentCode);
            parentCode = jsonObject.getString("parentCode");
            parentIds.add(0, jsonObject.getString("khtId"));
        }
        return parentIds;
    }

   //重关系表获取数据
    private Map<String, String>getThirdDepartmentMap(String companyNo){
        Map<String,String>map=new HashMap<String, String>();
        List<ThirdDepartment> thirdEmployeeList=jdbcSession.findArray(ThirdDepartment.class).eq("companyNo",companyNo).exe();
        thirdEmployeeList.forEach(item->{
            map.put(item.getThirdId(),item.getKhtId());
        });
        return map;
    }
    /**
     * 解析部门信息、封装成JSONArray返回
     * /userApi/v1/synUserInfo
     * 递归调用、分页调用中海
     * @return
     * @param pageNum  页码
     * @param
     */
    private JSONObject analysisDepartmentData(int pageNum,ThirdEnterpriseConfig thirdEnterpriseConfig,Map<String, String>thirdEmployeeMap)throws Exception{

        JSONObject resultJson=null; //用来存接口调用返回
        if(Objects.nonNull(thirdEnterpriseConfig.getLepartmentLastTime())){
            String lepartmentLastTime= DateUtils.timestampToStr(thirdEnterpriseConfig.getLepartmentLastTime(),DateUtils.PATTERN_1);
            resultJson=pullDepartmentMapData(lepartmentLastTime,pageNum,thirdEnterpriseConfig.getExt());
        }else{
            resultJson=pullDepartmentMapData(null,pageNum,thirdEnterpriseConfig.getExt());
        }
        String resultCode = resultJson.getString("resultCode");
        JSONObject dataJson=resultJson.getJSONObject("data");
        return dataJson;
    }

    /**
     * 中海中台拉取数据
     * @param lepartmentLastTime 传了则增量、否则全量
     * @return
     */
    private JSONObject pullDepartmentMapData(String lepartmentLastTime,int pageNum,String ext){
        JSONObject extJson=JSONObject.parseObject(ext);
        String url=extJson.getString("url");
        String method="/userApi/v1/synOrg";
        String appKey=extJson.getString("appKey");
        String appSecret=extJson.getString("appSecret");
        String timestamp=getTimestamp();
        Map<String,Object>paramMap=new HashMap<String,Object>(); //参数
        Map<String,Object>hearderMap=new HashMap<String,Object>(); //请求头
        if(lepartmentLastTime!=null){
            paramMap.put("lepartmentLastTime",lepartmentLastTime);
        }
        paramMap.put("pageNum",pageNum);
        JSONObject jsonParam = new JSONObject(paramMap);
        JSONObject param=new JSONObject();
        param.put("param",jsonParam);
        String linkString=appKey+"_"+appSecret+"_"+timestamp+"_"+jsonParam.toJSONString();
        hearderMap.put("appKey",appKey);
        hearderMap.put("timestamp", timestamp);
        String sign=MD5.MD5Encode(linkString);
        hearderMap.put("sign",sign);
        String result= HttpUtils.sendByForm(url+method,hearderMap,param);
        if(result!=null){
            return JSONObject.parseObject(result);
        }else{
            return null;
        }
    }

    private String getTimestamp(){
        return Long.toString(System.currentTimeMillis());
    }

}
